from django.http import HttpResponse, HttpResponseRedirect
from django.core import serializers
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType


def make_status_enabled(modeladmin, request, queryset):
    rows_updated = queryset.update(status='1')
    if rows_updated == 1:
        message_bit = "1 条记录"
    else:
        message_bit = "%s 条记录" % rows_updated
    modeladmin.message_user(request, "%s 成功被启用." % message_bit)


make_status_enabled.short_description = '启用'


def make_status_disabled(modeladmin, request, queryset):
    rows_updated = queryset.update(status='0')
    if rows_updated == 1:
        message_bit = "1 条记录"
    else:
        message_bit = "%s 条记录" % rows_updated
    modeladmin.message_user(request, "%s 成功被禁用." % message_bit)


make_status_disabled.short_description = '禁用'


def export_as_json(modeladmin, request, queryset):
    response = HttpResponse(content_type="application/json")
    serializers.serialize("json", queryset, stream=response)
    return response


export_as_json.short_description = '导出为Json'


# def export_selected_objects(modeladmin, request, queryset):
#     selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
#     ct = ContentType.objects.get_for_model(queryset.model)
#     return HttpResponseRedirect("/export/?ct=%s&ids=%s" % (ct.pk, ",".join(selected)))
